#encoding=utf-8
import xadmin,ujson,time,datetime,traceback,random,requests,os
#新页面不是model对应生成的，菜单url配置中的地址对应register_view的
from xadmin.views import BaseAdminPlugin, ModelFormAdminView, ModelAdminView, CommAdminView, csrf_protect_m
from xadmin.util import unquote
from django.utils.html import escape
from django import forms
from xadmin.layout import Fieldset, Main, Side, Row, FormHelper
from django.template.response import TemplateResponse
from django.utils.translation import ugettext as _
from django.utils.decorators import method_decorator
from django.http import HttpResponseRedirect
from django.views.decorators.debug import sensitive_post_parameters
from django.conf.urls import patterns, include, url
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response, HttpResponse, HttpResponseRedirect
from django.db.models import Count, Max, F, Q,Min,Sum
import websys.webconfig as webconfig
import websys.fun as fun
from django.db import transaction
from websys.models import (
    ServerInfo,EmailInfo,BlackList,Gift_Code,GiftCode
)
from  websys import (
    db_redis
)
from gm_site import settings
from websys.api import InterfaceFun,ProtocolHelper
class TestForm(forms.Form):
    """
    A form used to change the password of a user in the admin interface.
    """
    # error_messages = {
    #     'password_mismatch': _("The two password fields didn't match."),
    # }
    # password1 = forms.CharField(label=_("Password"),
    #                             widget=forms.PasswordInput)
    # password2 = forms.CharField(label=_("Password (again)"),
    #                             widget=forms.PasswordInput)

    def __init__(self,  *args, **kwargs):
        #self.user = user
        super(TestForm, self).__init__(*args, **kwargs)

PFINFO_LIST = []
#缓存平台列表
def getPlatformInfo_list():
    global PFINFO_LIST
    if not PFINFO_LIST:
        PFINFO_LIST=ServerInfo.objects.all().values('pf',"name")
getPlatformInfo_list()


URL2TITLE={'email':'邮件','forbid':'封号','speak':'禁言','gift_code':'礼物码','level_data':'等级数据生成'}#,'info':'详细信息查询&修改','task':'付费任务完成率','system':'系统阶段统计&排行','resource':'资源排行','prop':'道具'}
#自定义的页面
URL2DEFINE=['email','forbid','speak','gift_code','level_data']#,'task','system','resource','info','prop']

class ManagerView(ModelAdminView):
    model = ServerInfo
    this_form = TestForm
    common_obj={'jstype':'vendor','css_js':('xadmin.form.css','datepicker.css','xadmin.plugins.css', 'xadmin.page.form.js','xadmin.widget.datetime.js')}

    html_obj={}
    for ii in URL2TITLE:
        html_obj[ii]={'title':URL2TITLE[ii]}
        html_obj[ii].update(common_obj)

    @csrf_protect_m
    def get(self, request,_type):
        if not self.has_change_permission(request):
            raise 123#PermissionDenied
        self.obj = {}
        self.form = self.this_form()
        #print _type,'--CommonReportView-'
        self.htmlconfig=self.html_obj[_type]
        _title,_tmpurl=self.htmlconfig['title'],'commonreport.html'
        #if 'isDefine' in self.htmlconfig and self.htmlconfig['isDefine']==1:
        if _type in URL2DEFINE:
            _tmpurl = 'manager/%s.html' % (_type)
        self.title=_title

        self.tempurl=_tmpurl
        global PFINFO_LIST
        self.htmldata={'type':_type,'apps':PFINFO_LIST}

        return self.get_response()

    def get_media(self):
        media = super(ManagerView, self).get_media()
        if self.htmlconfig['jstype']=='static':
            for ii in self.htmlconfig['css_js']:
                file_type = ii.split('.')[-1]
                if file_type=='css':
                    media.add_css({'screen': [ii]})
                elif file_type=='js':
                    media.add_js((self.static(ii),))
            #tmp_media=self.static(*self.htmlconfig['css_js'])
        else:
            media+=self.vendor(*self.htmlconfig['css_js'])
        media = media+ self.form.media
        return media

    def get_context(self):
        #获取数据
        context = super(ManagerView, self).get_context()
        #print(context,'-------------------*****get_context*****',)
        helper = FormHelper()
        helper.form_tag = False
        self.form.helper = helper
        context.update({
            #'title': _('Change password: %s') % escape(unicode(self.obj)),
            'form': self.form,
            'has_delete_permission': False,
            'has_change_permission': True,
            'has_view_permission': True,
            'original': self.obj,
            #chong add
            'title':self.title,#_('My Information'),
            'account_view':True,
            'serverval':"服务器上的值",
            'htmldata':self.htmldata
        })
        return context

    #可以按不同的参数加载对应的页面
    def get_response(self):
        #print(self.get_context(),"----******get_response*******",self.admin_site.name)
        return TemplateResponse(self.request, [self.tempurl] , self.get_context(), current_app=self.admin_site.name)
        #return TemplateResponse(self.request, [ self.change_user_password_template or'xadmin/auth/user/change_password.html']
                               # , self.get_context(), current_app=self.admin_site.name)

#ajax请求页面
urlpatterns = patterns('',
                        url(r'^email', 'websys.view.otherdata.op_email', name='op_email'),
                        url(r'^em_quset', 'websys.view.otherdata.op_emquset', name='op_quset'),
                        url(r'^forbid', 'websys.view.otherdata.op_forbid', name='op_forbid'),
                        url(r'^fo_quset', 'websys.view.otherdata.op_foquset', name='op_foquset'),
                        url(r'^fo_delete', 'websys.view.otherdata.op_delete', name='op_delete'),
                        url(r'^speak', 'websys.view.otherdata.op_speak', name='op_speak'),
                        url(r'^sp_delete', 'websys.view.otherdata.op_spdelete', name='op_spdelete'),
                        url(r'^sp_quset', 'websys.view.otherdata.op_spquset', name='op_spquset'),
                        url(r'^gift_code', 'websys.view.otherdata.gift_code', name='gift_code'),
                        url(r'^level_datas', 'websys.view.otherdata.level_datas', name='level_datas'),

                       )

APP_KEY='nhmj_@12345'
import hashlib
#数字签名验证uid=xxx&gameid=xxx&sign=xxxx
def get_sorted_kv_list(param):
    sorted_keys = sorted(param)
    return [(k, param[k]) for k in sorted_keys]
def get_sign(param, ignore_keys=('sign'), app_key=APP_KEY):
    param = {k: str(v) for k, v in param.items() if k not in ignore_keys}
    kv_list = get_sorted_kv_list(param)
    string = "".join(["&".join(["=".join(x) for x in kv_list]), app_key])
    return hashlib.md5(string).hexdigest()

#获取多服务器
def getServers(obj):
    ser_arr=[]
    tmp_arr= obj.server.all()
    print '----------------',tmp_arr
    for ii_item in tmp_arr:
        ser_arr.append( ii_item.pf)
    return ser_arr



def create_gift_cdk2(itemid, server_id, gift_type,code_num,piciid,endtime,end_time):

    try:
        # conn = MySQLdb.connect(host=webconfig.con_db['host'], port=webconfig.con_db['port'],
        #                        user=webconfig.con_db['user'], passwd=webconfig.con_db['password'],
        #                        db=webconfig.con_db['database'])
        # cursor = conn.cursor()
        if int(gift_type)==0:
            for i in xrange(int(code_num)):
                cdk = "".join([str(random.randint(0, 9)) for i in range(8)])
                #print '-----=-=-=-=-=-=-=-=-',cdk
                #print server_id,'========='
                while 1:
                    # sqls="select * from t_gift_code where f_code=%s"%str(cdk)
                    # cursor.execute(sqls)
                    # data = cursor.fetchall()
                    num = Gift_Code.objects.filter(code=str(cdk)).exists()
                    if num:
                        cdk = "".join([str(random.randint(0, 9)) for i in range(8)])
                        continue
                    else:
                        break
                # each_cdk['type']=int(gift_type)
                # each_cdk['sids']=server_id
                # each_cdk['expire_ts']=int(end_time)
                # if '|' in str(itemid):
                #     many_list=str(itemid).split('|')
                #     for each in many_list:
                #         d_list=str(each).split('*')
                #         id_number[str(d_list[0])]=int(d_list[1])
                # else:
                #     d_list = str(itemid).split('*')
                #     id_number[str(d_list[0])] = int(d_list[1])
                # each_cdk['items']=id_number
                # cdk_dict[str(cdk)]=each_cdk
                # if server_id:
                #     sql = "INSERT INTO t_gift_code (f_serial_no, f_is_plat, f_server_code, f_origin, f_expired_utc, f_items, f_gift_type, f_activity_id, f_gift_num, f_code) "
                #     sql += "VALUES ( %s, 1, %s, '', %d, '%s', %d, %d,1, '%s');" % \
                #            (str(piciid), server_id, int(endtime),str(itemid),int(gift_type),int(actid),str(cdk))
                # else:
                #     sql = "INSERT INTO t_gift_code (f_serial_no, f_is_plat, f_origin, f_expired_utc, f_items, f_gift_type, f_activity_id, f_gift_num, f_code) "
                #     sql += "VALUES ( %s, 1,'', %d, '%s', %d, %d,1, '%s');" % \
                #            (str(piciid), int(endtime), str(itemid), int(gift_type), int(actid), str(cdk))
                # cursor.execute(sql)
                gift_info = Gift_Code()
                gift_info.server_code=server_id
                gift_info.expired_utc=endtime + ' 23:59:59'
                gift_info.items=itemid
                gift_info.gift_type=gift_type
                gift_info.activity_id=0
                gift_info.gift_num=1
                gift_info.code=cdk
                gift_info.serial_no=piciid
                gift_info.save()
        else:
            cdk = "".join([str(random.randint(0, 9)) for i in range(8)])
            # print '-----=-=-=-=-=-=-=-=-',cdk
            # print server_id,'========='
            while 1:
                # sqls="select * from t_gift_code where f_code=%s"%str(cdk)
                # cursor.execute(sqls)
                # data = cursor.fetchall()
                num = Gift_Code.objects.filter(code=str(cdk)).exists()
                if num:
                    cdk = "".join([str(random.randint(0, 9)) for i in range(8)])
                    continue
                else:
                    break
            # each_cdk['type'] = int(gift_type)
            # each_cdk['sids'] = server_id
            # each_cdk['expire_ts'] = int(end_time)
            # if '|' in str(itemid):
            #     many_list = str(itemid).split('|')
            #     for each in many_list:
            #         d_list = str(each).split('*')
            #         id_number[str(d_list[0])] = int(d_list[1])
            # else:
            #     d_list = str(itemid).split('*')
            #     id_number[str(d_list[0])] = int(d_list[1])
            # each_cdk['items'] = id_number
            # cdk_dict[str(cdk)] = each_cdk
            # if server_id:
            #     sql = "INSERT INTO t_gift_code (f_serial_no, f_is_plat, f_server_code, f_origin, f_expired_utc, f_items, f_gift_type, f_activity_id, f_gift_num, f_code) "
            #     sql += "VALUES ( %s, 1, %s, '', %d, '%s', %d, %d,1, '%s');" % \
            #            (str(piciid), server_id, int(endtime),str(itemid),int(gift_type),int(actid),str(cdk))
            # else:
            #     sql = "INSERT INTO t_gift_code (f_serial_no, f_is_plat, f_origin, f_expired_utc, f_items, f_gift_type, f_activity_id, f_gift_num, f_code) "
            #     sql += "VALUES ( %s, 1,'', %d, '%s', %d, %d,1, '%s');" % \
            #            (str(piciid), int(endtime), str(itemid), int(gift_type), int(actid), str(cdk))
            # cursor.execute(sql)
            gift_info = Gift_Code()
            gift_info.server_code = server_id
            gift_info.expired_utc = endtime + ' 23:59:59'
            gift_info.items = itemid
            gift_info.gift_type = gift_type
            gift_info.gift_num = code_num
            gift_info.activity_id = 0
            gift_info.code = cdk
            gift_info.serial_no = piciid
            gift_info.save()

        return 0
    except:
         return -1,




@csrf_exempt
@login_required(login_url="/xadmin/")
def op_email(request):
    data = {'ret': -1,'rows':[],'msg':''}
    uid = request.POST['uid']
    servers=str(request.POST['server'])
    server = servers[:-1].split(',')
    title =request.POST['title']
    content =request.POST['content']
    propid = request.POST['propid']
    number = request.POST['number']
    print '--------',propid,number
    items = {}
    if propid and number:
        propids=str(propid).split(',')
        numbers=str(number).split(',')
        if len(propids)==len(numbers):
            for i in range(len(propids)):
                items[propids[i]]=int(numbers[i])
        else:
            data['msg']='道具id或数量格式错误!'
            data['ret'] = -1
            return HttpResponse(ujson.dumps(data))
    else:
        items=None
    print items,'=====================ssss============='
    if InterfaceFun.SENDMAIL(server, uid,content,items) == 0:
        data['ret']=-1
        data['msg']='同步到服务器不成功'
    else:
        for ii in server:
            try:
                with transaction.commit_on_success():
                    id=ServerInfo.objects.get(pf=ii)
                    email=EmailInfo()
                    email.title=title
                    email.content=content
                    email.uids=uid
                    email.propid=propid
                    email.number=number
                    email.save()
                    email.server.add(id)
                    email.save()
            except:
                data['msg'] = '发送服务器成功,写入记录失败!'
                data['code'] =-1
                return HttpResponse(ujson.dumps(data))
        data['ret'] = 0
        data['msg'] = '发送成功'

    return HttpResponse(ujson.dumps(data))



@csrf_exempt
@login_required(login_url="/xadmin/")
def op_emquset(request):
    data = {'ret': -1, 'rows': [], 'msg': 'scuuess'}
    email = EmailInfo.objects.all().order_by('-id')
    lists=[]
    for i in email:
        obj = {}
        obj['uids'] = i.uids
        server = i.server.all()
        for j in server:
            obj['server'] = j.pf
        obj['title'] = i.title
        obj['content'] = i.content
        obj['propid']=i.propid
        obj['number']=i.number
        lists.append(obj)
    data['ret'] = 0
    return HttpResponse(ujson.dumps(lists))





@csrf_exempt
@login_required(login_url="/xadmin/")
def op_forbid(request):
    data = {'ret': -1, 'rows': [], 'msg': ''}
    uid = request.POST['uid']
    servers=str(request.POST['server'])
    server = servers[:-1].split(',')
    times =request.POST['time']
    reason =request.POST['reason']
    start_time = datetime.datetime.now()
    delta = datetime.timedelta(hours=int(times))
    end_time = start_time + delta
    if InterfaceFun.LOGIN_SWITCH_UID(server,0,uid,fun.DateTimeToStamp(end_time)) == 0:
        data['ret']=-1
        data['msg']='同步到服务器不成功'
    else:
        for ii in server:
            try:
                with transaction.commit_on_success():
                    id = ServerInfo.objects.get(pf=ii)
                    black=BlackList()
                    black.uids=uid
                    black.start_time=start_time
                    black.end_time=end_time
                    black.status=0
                    black.reason=reason
                    black.operid=request.user.username
                    black.save()
                    black.server.add(id)
                    black.save()
            except:
                data['msg'] = '发送服务器成功,写入记录失败!'
                data['code'] =-1
                return HttpResponse(ujson.dumps(data))
        data['ret'] = 0
        data['msg'] = '发送成功'
    return HttpResponse(ujson.dumps(data))



@csrf_exempt
@login_required(login_url="/xadmin/")
def op_foquset(request):
    data = {'ret': -1, 'rows': [], 'msg': 'scuuess'}
    black = BlackList.objects.filter(status=0).order_by('-id')
    lists=[]
    for i in black:
        obj = {}
        obj['uids'] = i.uids
        server = i.server.all()
        for j in server:
            obj['server'] = j.pf
        obj['id']=i.id
        obj['s_time'] = str(i.start_time)
        obj['e_time'] = str(i.end_time)
        obj['reason']=i.reason
        obj['operid']=i.operid
        obj['detaile']=''
        lists.append(obj)
    data['ret'] = 0
    data['msg'] = '操作成功'
    return HttpResponse(ujson.dumps(lists))


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_delete(request):
    data = {'ret': -1, 'msg': 'scuuess'}
    ids =request.POST['id']
    uid = request.POST['uid']
    servers = str(request.POST['server'])
    server = []
    server.append(servers)
    times = str(request.POST['time'])
    end_time = time.mktime(time.strptime(times,'%Y-%m-%d %H:%M:%S'))
    if InterfaceFun.LOGIN_SWITCH_UID(server,1,uid,fun.DateTimeToStamp(end_time)) == 0:
        data['ret']=-1
        data['msg']='同步到服务器不成功'
    else:
        try:
            with transaction.commit_on_success():
                BlackList.objects.get(id=int(ids)).delete()
        except:
            data['msg'] = '发送服务器(解封)成功,删除记录失败!'
            data['code'] = -1
            return HttpResponse(ujson.dumps(data))
    data['ret'] = 0
    return HttpResponse(ujson.dumps(data))


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_prop(request):
    data = {'ret':-1,'msg':''}
    uid = request.POST['uid']
    server=request.POST['server']
    print '---------',server
    propid =request.POST['propid']
    number =request.POST['number']
    pr_list = str(propid).split(',')
    items ={}
    for i in pr_list:
        items[i]=number
    ser_arr = []
    ser_arr.append(server)
    print ser_arr,'=============='
    if InterfaceFun.DELITEMS(ser_arr,uid,items) ==0:
        data['ret']=-1
        data['msg']='同步到服务器不成功'
    else:
        data['ret'] = 0
    return HttpResponse(ujson.dumps(data))


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_speak(request):
    data = {'ret': -1, 'rows': [], 'msg': ''}
    uid = request.POST['uid']
    servers=str(request.POST['server'])
    server = servers[:-1].split(',')
    times =request.POST['time']
    reason =request.POST['reason']
    start_time = datetime.datetime.now()
    delta = datetime.timedelta(hours=int(times))
    end_time = start_time + delta
    if InterfaceFun.FORBID_SPEAK(server,uid,int(fun.DateTimeToStamp(end_time))) == 0:
        data['ret']=-1
        data['msg']='同步到服务器不成功'
    else:
        for ii in server:
            try:
                with transaction.commit_on_success():
                    id = ServerInfo.objects.get(pf=ii)
                    black=BlackList()
                    black.uids=uid
                    black.start_time=start_time
                    black.end_time=end_time
                    black.status=1
                    black.reason=reason
                    black.operid=request.user.username
                    black.save()
                    black.server.add(id)
                    black.save()
            except:
                data['msg'] = '发送服务器成功,写入记录失败!'
                data['code'] =-1
                return HttpResponse(ujson.dumps(data))
        data['ret'] = 0
        data['msg'] = '发送成功'
    return HttpResponse(ujson.dumps(data))



@csrf_exempt
@login_required(login_url="/xadmin/")
def op_spquset(request):
    data = {'ret': -1, 'rows': [], 'msg': 'scuuess'}
    black = BlackList.objects.filter(status=1).order_by('-id')
    lists=[]
    for i in black:
        obj = {}
        obj['uids'] = i.uids
        server = i.server.all()
        for j in server:
            obj['server'] = j.pf
        obj['id'] = i.id
        obj['s_time'] = str(i.start_time)
        obj['e_time'] = str(i.end_time)
        obj['reason']=i.reason
        obj['operid']=i.operid
        lists.append(obj)
    data['ret'] = 0

    return HttpResponse(ujson.dumps(lists))


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_spdelete(request):
    data = {'ret': -1, 'msg': 'scuuess'}
    ids =request.POST['id']
    uid = request.POST['uid']
    servers = str(request.POST['server'])
    server = []
    server.append(servers)
    if InterfaceFun.FORBID_SPEAK(server,uid,1) == 0:
        data['ret']=-1
        data['msg']='同步到服务器不成功'
    else:
        try:
            with transaction.commit_on_success():
                BlackList.objects.get(id=int(ids)).delete()
        except:
            data['msg'] = '发送服务器(解除禁言)成功,删除记录失败!'
            data['code'] = -1
            return HttpResponse(ujson.dumps(data))
    data['ret'] = 0
    return HttpResponse(ujson.dumps(data))




@csrf_exempt
@login_required(login_url="/xadmin/")
def gift_code(request):
    data = {'ret': -1, 'msg': 'scuuess'}
    itemid = request.POST['itemid']
    servers = request.POST['server']
    server = servers[:-1]
    if str(server)=='1':
        server='all'
    code_num = request.POST['code_num']
    gift_type = request.POST['gift_type']
    if int(code_num)>50000 and int(gift_type)==0:
        data['msg']='生成数量超过50000！'
        return HttpResponse(ujson.dumps(data))
    endtime = request.POST['endtime']
    piciid=request.POST['piciid']
    # if Gift_Code.objects.filter(serial_no=str(piciid)).exists():
    #     data['msg'] = '该批次ID已存在,请重新输入批次ID！'
    #     return HttpResponse(ujson.dumps(data))
    end_time=fun.TimeToStamp(endtime+' 23:59:59')

    code=create_gift_cdk2(itemid, server, gift_type,code_num,piciid,endtime,end_time)
    if code==-1:
        data['msg']='生成失败!'
        return HttpResponse(ujson.dumps(data))

    # server_list=[settings.server_id]
    # if InterfaceFun.SAVE_CDK(server_list,cdk_dic)==0:
    #     data['ret'] = -1
    #     data['msg'] = '同步生成失败成功'
    #     Gift_Code.objects.filter(activity_id=pici).delete()
    else:
        gift_info=GiftCode()
        gift_info.items=itemid
        gift_info.gift_type=gift_type
        gift_info.server_id=server
        gift_info.number=code_num
        gift_info.serial=piciid
        gift_info.endtime=endtime+' 23:59:59'
        gift_info.save()
        data['ret']=0
    return HttpResponse(ujson.dumps(data))






@csrf_exempt
@login_required(login_url="/xadmin/")
def level_datas(request):
    data = {'ret': -1, 'msg': ''}
    servers = str(request.POST['server'])
    server = servers[:-1].split(',')
    print '-----------ppppppppppppp',os.getcwd()
    os.system('python /data/Projects/html5/mdwsw/v1/tools/level_data/get_level_data.py %s'%str(servers))
    data['ret'] = 0
    data['msg'] = 'success'
    return HttpResponse(ujson.dumps(data))


#渲染注册请求页面,url配置
# xadmin.site.register_view(r'^core/$', CommonReportView,name='core_report')#核心数据
# xadmin.site.register_view(r'^recharge/$', CommonReportView,name='recharge_report')
# xadmin.site.register_view(r'^online/$', CommonReportView,name='online_report')
# xadmin.site.register_view(r'^props/$', CommonReportView,name='props_report')
# xadmin.site.register_view(r'^newloss/$', CommonReportView,name='newloss_report')
# xadmin.site.register_view(r'^loadloss/$', CommonReportView,name='loadloss_report')
xadmin.site.register_view(r'^otherdata/(.+)/$', ManagerView,name='user_%s')#各种按日，月，年汇总页面
